<template>
	<view class="ble">
		<cu-custom class="navBox" bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
		</cu-custom>

		<view class="bleBtn" style="display: flex;align-items: center;justify-content: center">
			<view v-if="!bleVal">搜索蓝牙设备</view>
			<view class="" v-else>关闭蓝牙搜索</view>
			<u-switch v-model="bleVal" class="btn" @change="bleBtnChange"></u-switch>
		</view>
		<!-- 蓝牙列表 -->
		<view class="bleList">
			<view v-for="(item,index) in deviceList" :key="index"
				style="height:120rpx;border-bottom:1rpx solid #ccc;padding: 10rpx 30rpx;" class="item">
				<text class="" style="padding-right:20rpx">信号强度: {{item.RSSI}}</text>
				<text class="">可连接性: {{item.connectable}}</text>
				<view class="">ID: {{item.deviceId}}</view>
				<view class="">设备名称: {{item.name}}</view>
				<text class="cntBtn" @click="itemClick(item)">连接</text>
			</view>
		</view>
	</view>
</template>

<script>
	import cuCustom from '../component/colorui/components/cu-custom.vue'
	export default {
		components: {
			cuCustom
		},
		data() {
			return {
				Custom: this.Custom,
				bleVal: false,
				deviceList: [],
				deviceId: ''
			};
		},
		onLoad() {},
		onHide() {
			this.bleVal = false
			this.deviceList = []
			uni.closeBluetoothAdapter({
				success(res) {}
			})
		},
		methods: {
			itemClick(item) {
				uni.showLoading({
					title: '连接中...',
				})
				let thit = this
				//data里面建立一个deviceId，存储起来
				this.deviceId = item.deviceId
				//连接蓝牙
				uni.createBLEConnection({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: this.deviceId,
					success(res) {
						//防止在这里面取不到this，古在外面用thit存储了this
						thit.stopBluetoothDevicesDiscovery()
						console.log(res)
						uni.hideLoading()
						uni.showToast({
							icon: "success",
							title: '蓝牙连接成功'
						})
						console.log("蓝牙连接成功")
						thit.getBLEDeviceServices()
					},
					fail(res) {
						uni.hideLoading()
						uni.showToast({
							icon: 'error',
							title: '连接失败'
						})
						console.log("蓝牙连接失败", res)
					}
				})
			},
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						this.loading = false
						console.log('停止搜索蓝牙设备:' + e.errMsg);
					},
					fail: e => {
						console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);
					}
				});
			},
			//获取蓝牙的所有服务
			getBLEDeviceServices() {
				setTimeout(() => {
					uni.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.deviceId,
						success: (res) => {
							// console.log("成功",res)
							console.log('device services:', res)
							//这里会获取到好多个services  uuid  我们只存储我们需要用到的就行，这个uuid一般硬件厂家会给我们提供
							res.services.forEach((item) => {
								if (item.uuid.indexOf("AE00") != -1) {
									this.serviceId = item.uuid;
									//进入特征
									this.getBLEDeviceCharacteristics()
								}
							})
						}
					})
				}, 1000)
			},
			//获取蓝牙特征
			getBLEDeviceCharacteristics() {
				console.log("进入特征");
				setTimeout(() => {
					uni.getBLEDeviceCharacteristics({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.deviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: this.serviceId,
						success: (res) => {
							console.log(res, '特征getBLEDeviceCharacteristics')
							this.characteristics = res.characteristics
							console.log(this.characteristics)
							//循环所有的uuid

							// for(let i=0;i<3;i++){
							// 	this.notifyBLECharacteristicValueChange(res.characteristics[i].uuid)
							// 	console.log(res.characteristics[i].uuid)
							// 	console.log(i,'i')
							// }

							res.characteristics.forEach((item) => {
								if (item.uuid.indexOf("AE02") != -1) {
									console.log('characteristicId:', item.uuid)
									//利用传参的形势传给下面的notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
							})

						},
						fail: (res) => {
							console.log(res)
						}
					})
				}, 1000)
			},
			bleServer() {
				const _this = this
				// 初始化蓝牙
				uni.openBluetoothAdapter({
					success(res) {
						//搜索-以微信硬件平台的蓝牙智能灯为例，主服务的 UUID 是 FEE7。传入这个参数，只搜索主服务 UUID 为 FEE7 的设备
						uni.startBluetoothDevicesDiscovery({
							// services: ['FEE7'],
							success(res) {
								// ArrayBuffer转16进度字符串示例
								function ab2hex(buffer) {
									const hexArr = Array.prototype.map.call(
										new Uint8Array(buffer),
										function(bit) {
											return ('00' + bit.toString(16)).slice(-2)
										}
									)
									return hexArr.join('')
								}
								// uni.getBluetoothDevices({
								// 	success(res) {
								// 		console.log(res)
								// 		if (res.devices[0]) {
								// 			console.log(ab2hex(res.devices[0].advertisData))
								// 		}
								// 	}
								// })
								uni.onBluetoothDeviceFound(function(res) {
									console.dir(res.devices[0])
									if (res.devices[0].name) {
										const idList = _this.deviceList.map((item) => item
											.deviceId)
										if (idList.includes(res.devices[0]
												.deviceId)) {} else {
											_this.deviceList.push(res.devices[0])
										}
									}
									// if (res.devices[0].advertisData) {
									// 	res.devices[0].advertisData = ab2hex(res.devices[0]
									// 		.advertisData)
									// }
								})
							}
						})
					},
					fail() {
						uni.showToast({
							title: '请打开系统蓝牙!',
							icon: 'error'
						})
						setTimeout(function() {
							_this.bleVal = false

						}, 1000);
					}
				})

			},
			bleBtnChange(e) {
				const _this = this
				if (e) {
					uni.vibrateLong({
						success: function() {
							// console.log('success');
						}
					});
					// 开始搜索蓝牙
					this.bleServer()
				} else {
					uni.closeBluetoothAdapter({
						success(res) {
							_this.deviceList = []
							uni.showToast({
								title: '已关闭',
								icon: 'success'
							})
						}
					})
				}
			}
		},
	}
</script>

<style lang="scss" scoped>
	.ble {
		padding: 30rpx 0;

		.bleBtn {
			border-bottom: 1rpx solid #999;
			padding-bottom: 10rpx;

			::v-deep .u-switch {
				margin-left: 30rpx;
			}

		}

		.bleList {
			height: 80vh;
			overflow-y: scroll;

			.item {
				position: relative;

				::v-deep .cntBtn {
					position: absolute;
					right: 10rpx;
					top: 50%;
					font-size: 24rpx;
					text-align: center;
					padding: 10rpx;
					background-color: #ccc;
					border-radius: 6rpx;
					transform: translateY(-50%);
				}
			}
		}
	}
</style>
